<?php

namespace app\admin\controller;

use function Sodium\randombytes_random16;
use think\Controller;
use think\Db;
use think\Model;
use think\Request;
use think\facade\Cache;
use Zewail\Api\Facades\JWT;
use Zewail\Api\JWT\Factories\Code;

class System extends Controller
{
   public function initialize(){
       error_reporting(5);//1+4
       //设置跨域头
       header('Access-Control-Allow-Origin: *');
       //token 验证登录信息是否有效
       $request = new Request();
       $g=$request->get();
       $p=$request->post();
       $token = '';
       (isset($g['token']) && !empty($g['token'])) and ($token = $g['token']);
       (isset($p['token']) && !empty($p['token'])) and ($token = $p['token']);
       if(empty($token)){
           js_code('
                    var str = localStorage.getItem("token");
                    if(str !=="" || str.length>0){
                        var preg = /(\?token=.*|\?.*)/i
                        var href = location.href.replace(preg,"");
                        location.href=(href+"?token="+localStorage.getItem("token")).replace(/[?]{2,}/g,"?");
                    }else{
                        location.href="/admin_login_out";
                    }   
           ');
       }
       $jwt = new \app\common\controller\publics\Jwt();
       if(!$jwt->is_token($g['token']) || empty(cookie('fwf_admin_name'))){
           $this->error('信息验证错误，请重新登录','/admin_login_out');
       }
   }

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //
    }

    /*菜单列表*/
    public function menu_list(Request $request){
        //检查权限
        power_check();

        $title = '菜单列表';
        //获取菜单
        $mca=['m'=>\think\facade\Request::module(),'c'=>\think\facade\Request::controller(),'a'=>\think\facade\Request::action()];
        $mca['mca'] = $mca['m'].'/'.$mca['c'].'/'.$mca['a'];
        $mca['ca'] = $mca['c'].'/'.$mca['a'];
        $new_menu = Cache::tag('menu')->get('menu');
        $this->assign('new_menu',$new_menu);
        $this->assign('mca',$mca);

        $this->assign('title',$title);


        //halt(url_param());

        /*******分页部分 start */
        $g = $request->get();
        $param = $request->param();
        ($param['page_rows']) or ($param['page_rows'] = 15);
        ($param['page']) or ($param['page'] = 1);
        //当前页数
        $g['page'] = $page = intval($param['page']);
        //每页的行数
        $g['page_rows'] = $rows = intval($param['page_rows']);
        //总行数
        $g['rowCount'] = $rowCount = Db::name('menu')->where('admin_id','in',[0])->order(['menu_order'=>'desc'])->count();
        $this->assign('get',$g);
        /*******分页部分 end  */

        //获取菜单列表
        $menu_list = Db::name('menu')->where('admin_id','in',[0])->order(['menu_order'=>'desc'])->select();
        $GLOBALS['tree']['pid'] = 'menu_pid';
        $GLOBALS['tree']['id'] = 'menu_id';
        $menu_list = get_leval_list(1,2,$menu_list);
        $menu_list = array_slice($menu_list,($page-1)*$rows,$rows);

        $this->assign('menu_list',$menu_list);

        return $this->fetch();
    }
    /*编辑菜单--添加，修改*/
    public function menu_edit(Request $request){
        //检查权限
        power_check();
        //获取菜单
        $mca=['m'=>\think\facade\Request::module(),'c'=>\think\facade\Request::controller(),'a'=>\think\facade\Request::action()];
        $mca['mca'] = $mca['m'].'/'.$mca['c'].'/'.$mca['a'];
        $mca['ca'] = $mca['c'].'/'.$mca['a'];
        $new_menu = Cache::tag('menu')->get('menu');
        $this->assign('new_menu',$new_menu);
        $this->assign('mca',$mca);

        $id = $request->param('id');

        $t = lang('menu_add');
        if($id){
            $t = lang('menu_edit');
        }
        $this->assign('title',$t);
        $menu = Db::name('menu')->where('admin_id','in',[0])->where('menu_id','=',$id)->find();
        $menu_list = Db::table('fwf_menu')->where('menu_pid','=',0)->select();
        $this->assign('menu',$menu);
        $this->assign('menu_list',$menu_list);
        return $this->fetch();
    }
    /*保存菜单*/
    public function menu_save(Request $request){
        //检查权限
        power_check();
        $id = $request->param('id');
        $p = $request->post();
        $menu_id = $p['menu_id'];

        $validate = new \app\admin\validate\System();
        if(!$validate->menu_save($p)){
            $err = $validate->getError();
            $this->error(array_shift($err));
        }else{
            $data=[
                'menu_pid'      => $p['menu_pid'],
                'menu_title'    => $p['menu_title'],
                'menu_icon'     => $p['menu_icon'],
                'menu_status'   => $p['menu_status'],
                'menu_order'    => $p['menu_order'],
                'menu_show'     => $p['menu_show'],
            ];
            $controller = Db::name('menu')->where('menu_id','=',$p['menu_pid'])->value('menu_name');
            $menu_name = explode('/',$p['menu_name']);
            if($controller){
                if(count($menu_name)>1 && !in_array($menu_name[0],[''])){
                    if(strtolower($controller) == strtolower($menu_name[0])){
                        $data['menu_name'] = $p['menu_name'];
                    }else{
                        $data['menu_name'] = $controller.'/'.$menu_name[1];
                    }
                }elseif (count($menu_name)===1 && !in_array($menu_name[0],[''])){
                    $data['menu_name'] = $controller.'/'.$p['menu_name'];
                }
            }else{
                if($p['menu_pid'] == 0 && count($menu_name) === 1 && !in_array($menu_name[0],[''])){
                    $data['menu_name'] = $p['menu_name'];
                }
            }
            if($menu_id){
                //修改
                $up_n = Db::name('menu')->where('menu_id','=',$menu_id)->data($data)->update();
                if($up_n){
                    fwf_log('修改菜单，修改的菜单ID：'.$menu_id.'，影响的行数：'.$up_n);
                }
                $this->success(lang('edit_success'),lang('url').'/system/menu_edit/id/'.$menu_id);

            }else{
                //添加
                //检测菜单是否重复
                $count = Db::name('menu')->where('menu_pid','=',$p['menu_pid'])->where('menu_name','=',$data['menu_name'])->count();
                if($count>0){
                    $this->error('菜单不能重复','/system/menu_edit/id/?token='.$p['token']);
                }
                $insert_id = Db::name('menu')->insertGetId($data);
                if($insert_id){
                    fwf_log('添加菜单，添加的菜单ID：'.$insert_id);
                    $this->success(lang('add_success'),lang('url').'/System/menu_list');
                }
                $this->error(lang('add_fail'),lang('url').'/System/menu_list');
            }
        }
    }
    /*删除菜单*/
    public function menu_del(Request $request){
        //检查权限
        power_check();

        $id = $request->param('id');
        if($id){
            $del_n = Db::name('menu')->where('menu_id','=',$id)->delete();
            if($del_n){
                fwf_log('删除菜单，删除的菜单ID：'.$id.'，删除的行数：'.$del_n);
                $this->redirect(lang('url').'/System/menu_list');
            }
        }
        $this->error(lang('del_fail'));
    }
    /*异步修改菜单信息*/
    public function menu_edit_ajax(Request $request){
        //检查权限
        $ok=power_check(1);
        $g = $request->get();
        $admin_id = cookie('fwf_admin_id');
        if($ok){
            if($g['id']!='' && $g['f'] && $g['v']){
                $up_n = Db::name('menu')->where('menu_id','=',$g['id'])->data([ $g['f'] => $g['v'] ])->update();
                if($up_n){
                    fwf_log('异步修改菜单信息，修改的ID：'.$g['id'].'，修改的字段：'.$g['f'].'，操作管理员ID：'.$admin_id);
                    return_json(1,1,lang('edit_success'));
                }
            }
        }
        return_json(0,2,lang('edit_fail'));

    }



    /*变量列表*/
    public function variable_list(){
        //检查权限
        power_check();
        //获取菜单
        $mca=['m'=>\think\facade\Request::module(),'c'=>\think\facade\Request::controller(),'a'=>\think\facade\Request::action()];
        $mca['mca'] = $mca['m'].'/'.$mca['c'].'/'.$mca['a'];
        $mca['ca'] = $mca['c'].'/'.$mca['a'];
        $new_menu = Cache::tag('menu')->get('menu');
        $this->assign('new_menu',$new_menu);
        $this->assign('mca',$mca);

        return $this->fetch();
    }
    /*编辑变量--添加，修改*/
    public function variable_edit(Request $request){
        //检查权限
        power_check();
        //获取菜单
        $mca=['m'=>\think\facade\Request::module(),'c'=>\think\facade\Request::controller(),'a'=>\think\facade\Request::action()];
        $mca['mca'] = $mca['m'].'/'.$mca['c'].'/'.$mca['a'];
        $mca['ca'] = $mca['c'].'/'.$mca['a'];
        $new_menu = Cache::tag('menu')->get('menu');
        $this->assign('new_menu',$new_menu);
        $this->assign('mca',$mca);

    }
    /*保存变量信息*/
    public function variable_save(Request $request){
        $id = $request->param('id');
    }
    /*删除变量*/
    public function variable_del(Request $request){

    }
    /*异步修改变量信息*/
    public function variable_edit_ajax(Request $request){

    }

    /*日志列表*/
    public function log_list(Request $request){
        //检查权限
        power_check();
        $title = '日志列表';
        //获取菜单
        $mca=['m'=>\think\facade\Request::module(),'c'=>\think\facade\Request::controller(),'a'=>\think\facade\Request::action()];
        $mca['mca'] = $mca['m'].'/'.$mca['c'].'/'.$mca['a'];
        $mca['ca'] = $mca['c'].'/'.$mca['a'];
        $new_menu = Cache::tag('menu')->get('menu');
        $this->assign('new_menu',$new_menu);
        $this->assign('mca',$mca);

        $this->assign('title',$title);

        /*******分页部分 start */
        $g = $request->get();
        $param = $request->param();
        //总行数
        $rowCount = Db::name('log')->order(['id'=>'desc'])->count();
        paging($rowCount,$param,$g);
        $this->assign('get',$g);
        /*******分页部分 end  */

        //日志列表
        $log_list = Db::name('log')->order(['id'=>'desc'])->limit(($g['page']-1)*$g['page_rows'],$g['page_rows'])->select();
        $this->assign('log_list',$log_list);

        return $this->fetch();
    }
    /*保存日志*/
    public function log_save(){

    }
    /*删除日志*/
    public function log_del(Request $request){

    }

}
